#!/bin/bash
#Install keepalived、nginx
yum install -y keepalived nginx
mkdir /etc/conf/
mkdir /etc/nginx/ssl/
mv /etc/keepalived/keepalived.conf /etc/conf/keepalived.conf
mv /etc/nginx/nginx.conf /etc/conf/nginx.conf
#Write nginx.conf
#Get cups
cpus=$(grep -c processor /proc/cpuinfo)
cat>/etc/nginx/nginx.conf<<EOF
user root;
worker_processes $cpus;
events {
    worker_connections 1024;
    multi_accept on;
    use epoll;
}
http {
    sendfile            on;
    tcp_nopush          on;
    tcp_nodelay         on;
    keepalive_timeout   65;
    types_hash_max_size 4096;
    include             /etc/nginx/mime.types;
    default_type        application/octet-stream;
    include /etc/nginx/conf.d/*.conf;
    upstream webserver {
    }
    server {
        listen 443 ssl;
        server_name  localhost;
        ssl_certificate "/etc/nginx/ssl/$3";
        ssl_certificate_key "/etc/nginx/ssl/$4";
        ssl_session_cache shared:SSL:1m;
        ssl_session_timeout  10m;
        ssl_ciphers HIGH:!aNULL:!MD5;
        ssl_prefer_server_ciphers on;
EOF
echo -e "        add_header backendCode \$upstream_status;\n        add_header BackendIP \"\$upstream_addr;\" always;" >> /etc/nginx/nginx.conf
cat>>/etc/nginx/nginx.conf<<EOF
        location /{
            proxy_pass https://webserver;
            proxy_connect_timeout 5s;
        }
    }
    server {
        listen 80;
        server_name localhost;
EOF
echo -e "        add_header backendCode \$upstream_status;\n        add_header BackendIP \"\$upstream_addr;\" always;" >> /etc/nginx/nginx.conf
cat>>/etc/nginx/nginx.conf<<EOF
        location /{
            proxy_pass http://webserver;
            proxy_connect_timeout 5s;
        }
    }
}
EOF
#Add servers
RIPListString=$2
RIPList=(${RIPListString//,/ })
for rip in ${RIPList[@]}
do
   sed -i "18 i \        server $rip weight=1 max_fails=1 fail_timeout=10;" /etc/nginx/nginx.conf
done
#Write keepalived.conf
cat>/etc/keepalived/keepalived.conf<<EOF
! Configuration File for keepalived
global_defs {
    router_id nginx_backup
}
vrrp_script check_nginx {
    script "/etc/keepalived/check_nginx_status.sh"
    interval 2
    weight -5
    rise 1
    fall 2
}
vrrp_instance VI_1 {
    state BACKUP
    interface eth0
    virtual_router_id 51
    priority 99
    advert_int 1
    authentication {
        auth_type PASS
        auth_pass 1111
    }
    virtual_ipaddress {
        $1
    }
    track_script {
        check_nginx
    }
}
EOF
wget -P /etc/keepalived/ https://documentation-samples.obs.cn-north-4.myhuaweicloud.com/solution-as-code-publicbucket/solution-as-code-moudle/build-a-highly-available-seven-layer-load-balancer/userdata/check_nginx_status.sh
chmod 777 /etc/keepalived/check_nginx_status.sh
systemctl start nginx
systemctl enable nginx
systemctl start keepalived
systemctl enable keepalived